<template>
  <j-modal
    :title="editId ? `编辑采购单(单据号：${formData.orderNo})` : '新增采购单'"
    :width="1350"
    :visible="modalVisible"
    :maskClosable="false"
    switchFullscreen
    @cancel="clickCancel"
  >
    <a-spin :spinning="submitLoading">
      <a-form-model ref="form" :model="formData" :rules="rules">
        <a-divider orientation="left"> 基本信息 </a-divider>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="采购人" prop="purchaser" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                v-model="formData.purchaser"
                placeholder="请选择采购人"
                url="/sys/user/getAllUsernameByOrg"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="成本中心" prop="costCenterId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                ref="costCenterId"
                placeholder="请选择成本中心"
                v-model="formData.costCenterId"
                :allowClear="false"
                url="/sys/costCenter/queryAllByUserId"
                @change="changeSettlementOrg"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购方式" prop="purchaseWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择采购方式"
                v-model="formData.purchaseWay"
                dictCode="purchase_way"
                :allowClear="false"
                @change="changePurchaseWay"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="收货仓库" prop="warehouse" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                v-model="formData.warehouse"
                placeholder="请选择收货仓库"
                url="/hzkj-wms/wms/warehouse/queryWarehouseByUserId?type=1"
                :optionDiy="optionWarehouseDiy"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="运输方式" prop="transportWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择运输方式"
                v-model="formData.transportWay"
                dictCode="purchase_transport_way"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="预计到货时间"
              prop="expectArrivalTime"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker
                v-model="formData.expectArrivalTime"
                valueFormat="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择预计到货时间"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-show="formData.purchaseWay == '1'">
            <a-form-model-item
              label="买家留言"
              prop="buyerRemark"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea
                v-model="formData.buyerRemark"
                rows="2"
                placeholder="此处填写向1688下单时的买家留言"
                :maxLength="128"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="给仓库留言"
              prop="warehouseRemark"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea v-model="formData.warehouseRemark" rows="2" placeholder="请输入留言" :maxLength="128" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              prop="remark"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea v-model="formData.remark" rows="2" placeholder="请输入备注" :maxLength="128" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left"> 产品费用 </a-divider>
        <div class="btn-box">
          <a-button type="primary" icon="plus" @click="clickAddProduct" style="margin-right: 10px">添加产品</a-button>
          <a-alert message="允许添加多个供应商产品，不同供应商保存草稿后会按照供应商拆分为多个采购单。" banner />
        </div>
        <a-table
          bordered
          :pagination="false"
          :scroll="{ x: true, y: 400 }"
          :columns="formColumns"
          :data-source="formData.productDetailList"
          rowKey="skuCode"
        >
          <template #imgSlot="text, record">
            <a-popover trigger="hover" placement="right">
              <template #content>
                <div class="popover-preview-box">
                  <img :src="record.imgUrl" />
                </div>
              </template>
              <viewer :images="[record.imgUrl]" class="img-box">
                <img v-show="record.imgUrl" class="sku-img" :src="record.imgUrl" />
              </viewer>
            </a-popover>
          </template>
          <template #detailSlot="text, record">
            <div>类目:{{ record.categoryName }}</div>
            <div>名称:{{ record.nameCn }}</div>
            <div>颜色/尺寸:{{ record.color }};{{ record.size }}</div>
            <div>单品规格(cm):{{ record.singleSpec }}</div>
            <div>毛重(KG):{{ record.gw }}</div>
            <div>
              质检方式:<span v-if="record.qualityType == 1">免检</span><span v-if="record.qualityType == 3">全检</span
              ><span v-if="record.qualityType == 2">抽检</span>
            </div>
          </template>
          <template #supplierSlot="text, record">
            <template v-if="record.supplierId">
              <div>供应商:{{ record.supplierName }}</div>
              <div class="link-item">
                <div>采购链接:</div>
                <a-tooltip :overlayStyle="{ 'min-Width': '700px' }">
                  <template slot="title"> {{ record.url || '-' }} </template>
                  <div class="link">
                    {{ record.url || '-' }}
                  </div>
                </a-tooltip>
              </div>
              <div class="attribute-item">
                <div class="name">属性：</div>
                <div v-if="record.supplierType == 1">
                  <div v-for="item1 in record.attribute" :key="item1.attributeID">
                    {{ item1.attributeName }}:
                    <span v-for="(val2, index2) in item1.checkVal" :key="index2">{{ val2 }}；</span>
                  </div>
                </div>
                <div v-else>{{ record.attribute || '-' }}</div>
              </div>
              <div>最低起订量:{{ record.lowCount }}</div>
            </template>
            <template v-else>
              <div class="c-red">未找到供应商</div>
            </template>
            <div>
              <a
                @click="
                  productId = record.pdArchiveId
                  productSupperId = record.productSupperId
                  showSupplierModal = true
                "
                >匹配供应商</a
              >
              <a style="margin-left: 20px" @click="clickAddSupplier(record)">新增供应商</a>
            </div>
          </template>
          <template #specSlot="text, record">
            <div>
              供应商规格:
              <span v-if="record.supplierId" :class="{ 'c-red': record.specsSup > 1 }">{{ record.specsSup }}</span
              ><span v-else>-</span>/组
            </div>
            <div>
              入库规格:<span v-if="record.supplierId" :class="{ 'c-red': record.specsMy > 1 }">{{
                record.specsMy
              }}</span
              ><span v-else>-</span>/组
            </div>
            <a-tooltip placement="top">
              <template slot="title">
                供应商规格{{ record.specsSup }}：代表向供应商下单1个含{{ record.specsSup }}件；入库规格{{
                  record.specsMy
                }}：代表仓库按照{{ record.specsMy }}个 1 组入库。
              </template>
              <a-icon type="info-circle" />
            </a-tooltip>
          </template>
          <template #numTitle>
            <span class="c-red">*</span>采购数量
            <div>(仓库应收)</div></template
          >
          <template #numSlot="text, record, index">
            <a-form-model-item
              :prop="'productDetailList.' + index + '.purchaseQuantity'"
              :rules="{
                required: true,
                message: '数量不能为空',
                trigger: 'blur',
              }"
            >
              <a-input-number v-model="record.purchaseQuantity" :min="1" :max="99999999" :step="1" :precision="0" />
            </a-form-model-item>
          </template>
          <template #unitPriceTitle> <span class="c-red">*</span>采购单价(元)</template>
          <template #unitPriceSlot="text, record, index">
            <div v-if="formData.purchaseWay == '1'">待1688下单返回</div>
            <a-form-model-item
              v-else
              :prop="'productDetailList.' + index + '.unitPrice'"
              :rules="{
                required: true,
                message: '单价不能为空',
                trigger: 'blur',
              }"
            >
              <a-input-number v-model="record.unitPrice" :min="0" :max="999999.999" :step="1" :precision="3" />
            </a-form-model-item>
          </template>
          <template #remarkSlot="text, record">
            <a-textarea v-model="record.warehouseRemark" rows="3" placeholder="请输入留言" :maxLength="128" />
          </template>
          <span slot="action" slot-scope="text, record, index">
            <a @click="delProduct(index)">删除</a>
          </span>
        </a-table>
        <a-row v-show="formData.purchaseWay == '2'" style="margin-top: 15px">
          <a-col :span="5">
            <a-form-model-item
              label="运费"
              prop="totalShippingFee"
              :rules="{ required: formData.purchaseWay == '2', message: '请输入运费!' }"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input-number
                v-model="formData.totalShippingFee"
                :min="0"
                :max="999999.999"
                :step="1"
                :precision="3"
                style="width: 80%"
              /><span class="input-number-unit">元</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="10">
            <a-form-model-item label="跟踪号" prop="trackingNumber" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-search
                v-model="formData.trackingNumber"
                placeholder="请输入后点击‘添加’(可英文逗号分隔一次添加多个)"
                @search="createTrackingNumber"
              >
                <a-button slot="enterButton">添加</a-button>
              </a-input-search>
            </a-form-model-item>
          </a-col>
          <a-col :span="9">
            <a-tag
              style="margin-bottom: 5px"
              v-for="(item, index) in trackingNumberArr"
              :key="index"
              :closable="true"
              @close.prevent="trackingNumberArr.splice(index, 1)"
            >
              {{ item }}
            </a-tag>
          </a-col>
        </a-row>
        <a-divider orientation="left"> 支付信息 </a-divider>
        <div class="pay-msg">
          单据费用：采购总量 = <span class="c-red">{{ totalPurchaseQuantity }}</span
          >，采购总金额 = <span class="c-red">{{ totalAmount }}</span>
          <span v-if="this.formData.purchaseWay != '1'">元</span>
        </div>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="结算类型" prop="settlementType" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.settlementType"
                dictCode="purchase_settlement_type"
                :disabled="formData.purchaseWay == '1'"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="结算方式" prop="settlementWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.settlementWay"
                dictCode="purchase_settlement_way"
                :disabled="formData.purchaseWay == '1'"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="支付方式" prop="paymentWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.paymentWay"
                dictCode="purchase_payment_way"
                :disabled="formData.purchaseWay == '1'"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-show="formData.purchaseWay == '2'">
            <a-form-model-item label="供应商订单" prop="supplierOrderNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.supplierOrderNo" placeholder="请输入供应商订单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-show="formData.purchaseWay == '2'">
            <a-form-model-item label="支付单号" prop="paymentOrderNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.paymentOrderNo" placeholder="请输入支付单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-show="formData.purchaseWay == '2'">
            <a-form-model-item label="付款时间" prop="paymentTime" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker
                showTime
                valueFormat="YYYY-MM-DD HH:mm:ss"
                v-model="formData.paymentTime"
                style="width: 100%"
                placeholder="请选择付款时间"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-show="formData.purchaseWay == '2'">
            <a-form-model-item label="支付凭证" prop="paymentVoucher" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload-oss v-model="formData.paymentVoucher" fileType="file" :number="1" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="clickCancel"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit('draft')"> 保存为草稿 </a-button>
      <a-button v-show="formData.purchaseWay == '2'" type="primary" :loading="submitLoading" @click="submit('submit')">
        提交
      </a-button>
      <a-button v-show="formData.purchaseWay == '1'" type="primary" :loading="submitLoading" @click="click1688Pay">
        1688下单并提交
      </a-button>
    </template>
    <!-- 产品选择弹窗 -->
    <product-check-modal
      v-if="showProductCheck"
      :defaultParam="{ deptCode: formData.costCenterId }"
      :visible.sync="showProductCheck"
      :defaultData="formData.productDetailList"
      @submit="submitProductCheck"
    >
      <a-alert
        slot="hint"
        message="组合产品会按照组合比例拆分为子产品采购，列表仅显示产品对应的默认供应商"
        banner
        style="margin-bottom: 10px"
      />
    </product-check-modal>
    <!-- 供应商选择弹窗 -->
    <supplier-modal
      v-if="showSupplierModal"
      :visible.sync="showSupplierModal"
      :purchaseWay="formData.purchaseWay"
      :productId="productId"
      :productSupperId="productSupperId"
      @submit="submitSupplier"
    />
    <!-- 1688下单弹窗 -->
    <pay-order-1688-modal
      ref="payOrder1688Modal"
      @submit="
        modalVisible = false
        $emit('submit')
      "
    />
    <!-- 添加1688供应商弹窗 -->
    <supplier-1688-modal
      v-if="show1688SupplierModal"
      :visible.sync="show1688SupplierModal"
      @submit="submit1688AddSupplier"
    />
    <!-- 添加其他供应商弹窗 -->
    <supplier-other-add-modal ref="supplierOtherAddModal" @submit="submitOtherAddSupplier" />
  </j-modal>
</template>

<script>
import { formatAmount, parseNumber } from '@/utils/number'
import { getAction, postAction, putAction } from '@/api/manage'

import Supplier1688Modal from '@/components/business/Supplier1688Modal.vue'
import ProductCheckModal from '@/components/business/ProductCheckModal.vue'
import SupplierModal from './SupplierModal.vue'
import PayOrder1688Modal from './PayOrder1688Modal.vue'
import SupplierOtherAddModal from './SupplierOtherAddModal.vue'

export default {
  components: { Supplier1688Modal, ProductCheckModal, SupplierModal, PayOrder1688Modal, SupplierOtherAddModal },
  props: {
    // 要编辑的id，为空表示新增
    editId: {
      type: String,
      default: '',
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      submitLoading: false,
      showProductCheck: false,
      show1688SupplierModal: false,
      productId: '',
      productSupperId: '',
      showSupplierModal: false,
      trackingNumberArr: [], // 跟踪号临时数据，提交时要转义
      formData: {
        purchaser: this.$store.getters.userInfo.username,
        costCenterId: '',
        purchaseWay: '1',
        warehouse: '',
        transportWay: '',
        expectArrivalTime: '',
        warehouseRemark: '',
        remark: '',
        productDetailList: [],
        totalShippingFee: 0,
        trackingNumber: '',
        settlementType: '1',
        settlementWay: '1',
        paymentWay: '1',
      }, // 表单数据
      rules: {
        purchaser: [{ required: true, message: '请选择采购人!' }],
        costCenterId: [{ required: true, message: '请选择成本中心!' }],
        purchaseWay: [{ required: true, message: '请选择采购方式!' }],
        warehouse: [{ required: true, message: '请选择收货仓库!' }],
        transportWay: [{ required: true, message: '请选择运输方式!' }],
        settlementType: [{ required: true, message: '请选择结算类型!' }],
        settlementWay: [{ required: true, message: '请选择结算方式!' }],
        paymentWay: [{ required: true, message: '请选择支付方式!' }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        add: `/hzkj-purchase/purchase/order/info/add`,
        edit: `/hzkj-purchase/purchase/order/info/edit`,
        queryById: `/hzkj-purchase/purchase/order/info/detail`,
        queryLastUtilPrice: `/hzkj-purchase/purchase/product/queryLastUtilPrice`,
      },
    }
  },
  computed: {
    formColumns() {
      let arr = [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender(t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: 'SKU',
          width: 130,
          align: 'center',
          dataIndex: 'skuCode',
        },
        {
          title: '主图',
          dataIndex: 'imgSlot',
          width: 110,
          align: 'center',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: '产品信息',
          width: 200,
          scopedSlots: { customRender: 'detailSlot' },
        },
        {
          title: '供应商',
          width: 300,
          scopedSlots: { customRender: 'supplierSlot' },
        },
        {
          title: '采购入库关系',
          width: 150,
          scopedSlots: { customRender: 'specSlot' },
        },
        {
          slots: { title: 'numTitle' },
          width: 130,
          align: 'center',
          scopedSlots: { customRender: 'numSlot' },
        },
        this.formData.purchaseWay == '1'
          ? {
              title: '下单数量(供应商)',
              width: 150,
              align: 'center',
              dataIndex: 'orderQuantity',
              customRender(t, record) {
                if (!record.purchaseQuantity || !record.specsMy || !record.specsSup) {
                  return 0
                }
                let purchaseQuantity = parseNumber(record.purchaseQuantity)
                let specsMy = parseNumber(record.specsMy)
                let specsSup = parseNumber(record.specsSup)
                return formatAmount((purchaseQuantity * specsMy) / specsSup, 4)
              },
            }
          : null,
        {
          title: '上次采购单价(含运费)',
          width: 150,
          align: 'center',
          dataIndex: 'lastUnitPrice',
        },
        {
          slots: { title: 'unitPriceTitle' },
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'unitPriceSlot' },
        },
        {
          title: '采购总价(元)',
          width: 120,
          align: 'center',
          customRender: (t, record) => {
            if (this.formData.purchaseWay == '1') {
              // 1688采购的金额信息需要等待1688返回
              if (!this.editId || ['1', '6'].includes(this.formData.status)) {
                // 如果是新增或者订单状态是草稿和取消的订单，则待下单返回
                return '待1688下单返回'
              } else {
                return record.totalPrice
              }
            } else {
              return formatAmount(parseNumber(record.unitPrice) * parseNumber(record.purchaseQuantity), 3)
            }
          },
        },
        {
          title: '给仓库留言',
          width: 180,
          align: 'center',
          scopedSlots: { customRender: 'remarkSlot' },
        },
        {
          title: '操作',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'action' },
        },
      ]

      return arr.filter((i) => i)
    },
    totalPurchaseQuantity() {
      if (!this.formData.productDetailList.length) {
        return 0
      }
      return this.formData.productDetailList.reduce((total, next) => {
        return total + parseNumber(next.purchaseQuantity)
      }, 0)
    },
    totalAmount() {
      if (this.formData.purchaseWay == '1') {
        // 1688采购的金额信息需要等待1688返回
        if (!this.editId || ['1', '6'].includes(this.formData.status)) {
          // 如果是新增或者订单状态是草稿和取消的订单，则待下单返回
          return '待下单返回'
        } else {
          return this.formData.totalAmount
        }
      } else {
        // 其他类型的采购为计算出的金额之和
        if (!this.formData.productDetailList.length) {
          return 0
        }
        let total = this.formData.productDetailList.reduce((total, next) => {
          return parseNumber(next.unitPrice) * parseNumber(next.purchaseQuantity) + total
        }, 0)
        return formatAmount(total + parseNumber(this.formData.totalShippingFee), 3)
      }
    },
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    optionWarehouseDiy(result) {
      return result.map((item) => {
        return {
          ...item,
          value: item.id,
          text: `${item.name}[${item.code}]`,
        }
      })
    },
    createTrackingNumber() {
      if (!this.formData.trackingNumber.trim()) {
        this.$message.warning('请输入跟踪号')
        return
      }
      this.trackingNumberArr = [...this.trackingNumberArr, ...this.formData.trackingNumber.split(',')]
      this.formData.trackingNumber = ''
    },
    changeSettlementOrg(id, oldId) {
      if (this.formData.productDetailList.length && oldId) {
        this.$confirm({
          content: (h) => {
            return h(
              'div',
              {
                domProps: {
                  innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">更换成本中心后需重新选择采购产品</div><span style="color: red">当前档案产品列表会清空</span>你还要继续吗？</div>`,
                },
              },
              []
            )
          },
          onOk: () => {
            this.formData.productDetailList = []
          },
          onCancel: () => {
            this.formData.costCenterId = oldId
          },
        })
      }
    },
    changePurchaseWay(type) {
      if (type == '1') {
        if (this.formData.productDetailList.some((i) => i.supplierType == '2')) {
          this.$message.warning('商品中存在非1688采购，不支持切换')
          this.formData.purchaseWay = '1'
          return
        }
        this.formData = {
          ...this.formData,
          settlementType: '1',
          settlementWay: '1',
          paymentWay: '1',
        }
      }
    },
    clickAddProduct() {
      if (!this.formData.costCenterId) {
        this.$message.warning('请选择成本中心')
        return
      }
      if (!this.formData.purchaseWay) {
        this.$message.warning('请选择采购方式')
        return
      }
      this.showProductCheck = true
    },
    //删除产品
    delProduct(index) {
      this.formData.productDetailList.splice(index, 1)
    },
    queryLastUtilPrice(skus) {
      return new Promise((resolve) => {
        getAction(this.url.queryLastUtilPrice, { skus }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    async submitProductCheck(arr) {
      let endArr = [] // 最终需要保存的数据
      const joinDataFun = (i) => {
        // 新添加的单品
        let data = {
          pdArchiveId: i.id,
          category: i.category,
          categoryName: i.category_dictText,
          color: i.hzArchiveInfoOtherList[0].color,
          imgUrl: i.hzArchiveInfoImgsList.find((i2) => i2.izMaster == 1).url,
          heig: i.hzArchiveInfoOtherList[0].heig,
          len: i.hzArchiveInfoOtherList[0].len,
          widt: i.hzArchiveInfoOtherList[0].widt,
          gw: i.hzArchiveInfoOtherList[0].gw,
          singleSpec:
            i.hzArchiveInfoOtherList[0].len +
            '*' +
            i.hzArchiveInfoOtherList[0].widt +
            '*' +
            i.hzArchiveInfoOtherList[0].heig,
          nameCn: i.nameCn,
          nameEn: i.nameEn,
          purchaseQuantity: undefined,
          qualityType: i.hzArchiveInfoOtherList[0].qualityType,
          size: i.hzArchiveInfoOtherList[0].size,
          skuCode: i.skuCode,
          totalPrice: undefined,
          unitPrice: undefined,
          warehouseRemark: '',
        }
        // 以下是供应商信息
        const defaultSupplier = (i.hzArchiveInfoSupplierList || []).find((i2) => i2.izDefault == 1)
        if (defaultSupplier) {
          if (this.formData.purchaseWay == '2' || defaultSupplier.type == 1) {
            // 当采购类型为其他时可以添加任意类型供应商，如果是16888采购，则只能添加16888供应商
            data = {
              ...data,
              supplierType: defaultSupplier.type,
              supplierName: defaultSupplier.name,
              url: defaultSupplier.url,
              attribute: defaultSupplier.type == 1 ? JSON.parse(defaultSupplier.attribute) : defaultSupplier.attribute,
              lowCount: defaultSupplier.lowCount,
              specsMy: defaultSupplier.specsMy,
              specsSup: defaultSupplier.specsSup,
              offerId: defaultSupplier.offerId,
              specId: defaultSupplier.specId,
              supplierId: defaultSupplier.supplierId,
              productSupperId: defaultSupplier.id,
            }
          }
        }
        endArr.push(data)
      }
      arr.forEach((item) => {
        if (!item.constituteStatus) {
          // 说明是之前已经添加的产品，数据已经处理完成，直接加入列表
          endArr.push(item)
        } else {
          if (item.constituteStatus == 2) {
            // 新添加的组合产品，组合产品自动拆分为添加组合产品下的所有单品
            item.hzArchiveInfoCproductAllInfoList.forEach((i2) => {
              joinDataFun(i2)
            })
          } else {
            joinDataFun(item)
          }
        }
      })
      let filterData = this.$Jlodash.uniqBy(endArr, 'skuCode') //组合产品的子产品和单品可能重复，需要去重
      let lastUtilPriceObj = await this.queryLastUtilPrice(filterData.map((item) => item.skuCode).join(','))
      this.formData.productDetailList = filterData.map((item, index) => ({
        ...item,
        lastUnitPrice: lastUtilPriceObj[item.skuCode] || null,
      }))
    },
    submitSupplier(obj) {
      let index = this.formData.productDetailList.findIndex((i) => i.pdArchiveId == this.productId)
      let findItem = this.formData.productDetailList[index]
      this.$set(this.formData.productDetailList, index, {
        ...findItem,
        supplierType: obj.type,
        supplierName: obj.name,
        url: obj.url,
        attribute: obj.type == 1 ? JSON.parse(obj.attribute) : obj.attribute,
        lowCount: obj.lowCount,
        specsMy: obj.specsMy,
        specsSup: obj.specsSup,
        offerId: obj.offerId,
        specId: obj.specId,
        supplierId: obj.supplierId,
        productSupperId: obj.id,
      })
    },
    clickCancel() {
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">取消将不会保存当前单据的修改信息</div>你还要继续吗？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          this.modalVisible = false
        },
      })
      return false
    },
    submit(type) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.formData.productDetailList.length) {
            this.$message.warning('无采购产品，不允许提交单据')
            return
          }
          if (type == 'submit' && this.formData.productDetailList.some((i) => !i.supplierId)) {
            this.$message.warning('产品必须有供应商')
            return
          }
          let uniqArr = this.$Jlodash.uniqBy(this.formData.productDetailList, 'supplierId')
          if (type == 'submit' && uniqArr.length != 1) {
            this.$message.warning('采购单存在多个供应商，可保存为草稿后再下单')
            return
          }
          if (type == 'submit') {
            // 有跟踪号
            this.$confirm({
              content: (h) => {
                return h(
                  'div',
                  {
                    domProps: {
                      innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">提交单据后，采购单状态直接变更为“${
                        this.trackingNumberArr.length ? '在途' : '已付款'
                      }”</div>你还要继续吗？</div>`,
                    },
                  },
                  []
                )
              },
              onOk: () => {
                this.formSend({ operateType: 'submit' })
              },
            })
            return
          } else {
            this.formSend({ operateType: 'draft' })
          }
        }
      })
    },
    formSend(params = {}) {
      const sendData = JSON.parse(JSON.stringify(this.formData))
      sendData.trackingNumber = this.trackingNumberArr.join(',')
      sendData.productDetailList = sendData.productDetailList.map((item) => ({
        ...item,
        attribute: item.supplierType == 1 ? JSON.stringify(item.attribute) : item.attribute,
      }))
      this.submitLoading = true
      let request = this.editId ? putAction : postAction
      request(this.editId ? this.url.edit : this.url.add, { ...sendData, ...params })
        .then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$emit('submit')
            this.modalVisible = false
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    click1688Pay() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.formData.productDetailList.length) {
            this.$message.warning('无采购产品，不允许提交单据')
            return
          }
          if (this.formData.productDetailList.some((i) => !i.supplierId)) {
            this.$message.warning('产品必须有供应商')
            return
          }
          if (this.formData.productDetailList.some((i) => i.supplierType == 2)) {
            this.$message.warning('您下单的供应商存在非1688供应商，请重新选择供应商后下单')
            return
          }
          let findProduct = this.formData.productDetailList.find((i) => {
              let specIdSize = i.specId.split(',').length
              return !Number.isInteger((i.purchaseQuantity * i.specsMy) / i.specsSup / specIdSize)
            })
          if (findProduct) {
            this.$message.warning(`sku号为${findProduct.skuCode}的产品平台下单数量不为整数，请修改采购数量后再下单`)
            return
          }
          let uniqArr = this.$Jlodash.uniqBy(this.formData.productDetailList, 'supplierId')
          if (uniqArr.length != 1) {
            this.$message.warning('采购单存在多个供应商，可保存为草稿后再下单')
            return
          }
          const sendData = JSON.parse(JSON.stringify(this.formData))
          sendData.trackingNumber = this.trackingNumberArr.join(',')
          sendData.operateType = 'submit'
          sendData.productDetailList = sendData.productDetailList.map((item) => ({
            ...item,
            attribute: item.supplierType == 1 ? JSON.stringify(item.attribute) : item.attribute,
          }))
          this.$refs.payOrder1688Modal.api_open(this.formData.warehouse, null, sendData)
        }
      })
    },
    clickAddSupplier(record) {
      this.productId = record.pdArchiveId
      if (this.formData.purchaseWay == '1') {
        this.show1688SupplierModal = true
      } else {
        this.$refs.supplierOtherAddModal.api_open()
      }
    },
    // 添加1688供应商
    submit1688AddSupplier(obj) {
      let index = this.formData.productDetailList.findIndex((i) => i.pdArchiveId == this.productId)
      let findItem = this.formData.productDetailList[index]
      this.$set(this.formData.productDetailList, index, {
        ...findItem,
        supplierType: 1,
        supplierName: obj.name,
        url: obj.url,
        attribute: obj.attrList,
        lowCount: obj.productInfo.productSaleInfo.minOrderQuantity,
        specsMy: obj.specsMy,
        specsSup: obj.specsSup,
        offerId: obj.productInfo.openOfferId,
        specId: obj.specId,
        supplierId: obj.id,
      })
    },
    // 添加其他供应商
    submitOtherAddSupplier(data) {
      const obj = JSON.parse(JSON.stringify(data))
      let index = this.formData.productDetailList.findIndex((i) => i.pdArchiveId == this.productId)
      let findItem = this.formData.productDetailList[index]
      this.$set(this.formData.productDetailList, index, {
        ...findItem,
        supplierType: 2,
        supplierName: obj.supplierName,
        url: obj.url,
        attribute: '',
        lowCount: obj.lowCount,
        specsMy: obj.specsMy,
        specsSup: obj.specsSup,
        supplierId: obj.supplierId,
      })
    },
  },
  created() {
    // 有editId表示编辑账号
    if (this.editId) {
      // 编辑，需要回显
      this.submitLoading = true
      getAction(this.url.queryById, { id: this.editId }).then((res) => {
        if (res.success) {
          this.trackingNumberArr = res.result.trackingNumber ? res.result.trackingNumber.split(',') : []
          this.formData = {
            ...res.result,
            trackingNumber: '',
            productDetailList: res.result.productDetailList.map((i) => ({
              ...i,
              attribute: i.supplierType == '1' ? JSON.parse(i.attribute) : i.attribute,
            })),
          }
          if (this.formData.createBy) {
            delete this.formData.createBy
          }
          if (this.formData.createTime) {
            delete this.formData.createTime
          }
          if (this.formData.updateBy) {
            delete this.formData.updateBy
          }
          if (this.formData.updateTime) {
            delete this.formData.updateTime
          }
          this.submitLoading = false
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  },
}
</script>

<style lang="less" scoped>
.btn-box {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
}
.c-red {
  color: #ff4d4f;
}
.input-number-unit {
  display: inline-block;
  margin-left: -2px;
  width: 20%;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  background-color: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 0 4px 4px 0;
}

.pay-msg {
  font-weight: bold;
  font-size: 15px;
  padding: 5px 5px 15px;
}
.link-item {
  display: flex;
  .link {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
}
.attribute-item {
  display: flex;
  .name {
    flex-shrink: 0;
  }
}

/deep/ .ant-table-placeholder {
  padding: 0;
  border-top: none;
}
/deep/ .ant-table-hide-scrollbar {
  padding-right: 15px;
  scrollbar-color: #8b8b8b transparent;
  background: transparent;
  overflow: scroll hidden !important;
}
</style>
